package httpdemo;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import io.netty.handler.codec.http.HttpHeaders.Values;
/**
 * description
 *
 * @author Llx
 * @version v1.0.0
 * @since 2018/9/28
 */
public class NettyServerHandler extends SimpleChannelInboundHandler <FullHttpRequest> {
    StringBuilder sb = new StringBuilder();
    JSONArray jsonarray = new JSONArray();

    public NettyServerHandler() {
        jsonarray.add(getJsonObj("name", "ar.sear.ocalplay"));
        jsonarray.add(getJsonObj("name", "ar.sear.ticket"));
        jsonarray.add(getJsonObj("name", "ar.sear.tel"));
        jsonarray.add(getJsonObj("name", "ar.sear.surehotel"));
    }

    public JSONObject getJsonObj(String name, String value) {
        JSONObject jsonobj = new JSONObject();
        jsonobj.put(name, value);
        return jsonobj;
    }
    private HttpRequest request;
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }


    /**
     * 进入到handler后，首先执行channelRead ，然后调用channelRead0(ctx, msg)
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
       boolean isResponse = true;
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);

        //解析get请求参数 方式获取链接(url 可以看到的链接) 获取链接内容
        if (msg instanceof HttpRequest) {
            request = (HttpRequest) msg;
            String uri = request.getUri();
            System.out.println("Uri:" + uri);

            //获取
            QueryStringDecoder decoder = new QueryStringDecoder(msg.getUri());
            Map <String, List <String>> parame = decoder.parameters();
            for (Map.Entry <String, List <String>> entry : parame.entrySet()) {
                System.out.println(entry.getKey() + " : " + entry.getValue());
            }
        }

        //表单内容 获取表单内容
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            ByteBuf buf = content.content();
            System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
            buf.release();

            String res = "I am OK";
            if(isResponse){
                // 响应信息  创建Response时，直接赋值 给 content里面内容
                response = new DefaultFullHttpResponse(HTTP_1_1,
                        OK, Unpooled.wrappedBuffer(res.getBytes("UTF-8")));

                response.headers().set(CONTENT_TYPE, "text/plain");
                response.headers().set(CONTENT_LENGTH,
                        response.content().readableBytes());
                if (HttpHeaders.isKeepAlive(request)) {
                    response.headers().set(CONNECTION, Values.KEEP_ALIVE);
                }
                isResponse= false;
                ctx.write(response);
                ctx.flush();

            }

        }

        if(!isResponse){
            // 响应信息
            response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
            ByteBuf responseContentByteBuf = Unpooled.copiedBuffer(JSON.toJSONString(jsonarray, SerializerFeature.DisableCircularReferenceDetect).getBytes(Charset.forName("utf-8")));
            response.headers().set("Access-Control-Allow-Origin", "*");
            // 跨域
            response.headers().set(CONTENT_LENGTH, responseContentByteBuf.readableBytes());
            //手动设置 content里面内容
            response.content().writeBytes(responseContentByteBuf);
            responseContentByteBuf.release();
            //zuoyong?
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        }
    }


    /**
     * 进入到handler后，首先执行channelRead ，然后调用channelRead0(ctx, msg)
     * @param ctx
     * @param msg
     * @throws Exception
     */

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("ddddd");
        super.channelRead(ctx, msg);
    }
}